package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.order.WeixinPayService;
import com.qingcheng.service.seckill.SeckillOrdersService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WeiXinPayController {

    @Reference
    private SeckillOrdersService seckillOrdersService;

    @Reference
    private WeixinPayService weixinPayService;

    @GetMapping("/createNative")
    public Map createNative(String orderId){

        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("username: "+username);

        SeckillOrder seckillOrder = seckillOrdersService.queryByUsername(username);

        if(seckillOrder!=null){
            //判断订单支付状态为0，订单的用户是登录账号
            if("0".equals(seckillOrder.getStatus()) && username.equals(seckillOrder.getUserId()) ){
                return weixinPayService.createNative(seckillOrder.getId().toString(),seckillOrder.getMoney().intValue(),"http://qingcheng.vaiwan.com/wxpay/notify.do",username);
            }else{
                return null;
            }

        }else{
            return null;
        }
    }

    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request){
        System.out.println("支付成功，进行回调");

        InputStream inputStream;
        try {
            inputStream = request.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len=0;
            while((len = inputStream.read(buffer)) !=-1){
                outputStream.write(buffer,0,len);
            }
            outputStream.close();
            inputStream.close();

            String result = new String(outputStream.toByteArray(),"UTF-8");
            System.out.println(result);


                //1.对xml解析 map
                Map<String,String> map = WXPayUtil.xmlToMap(result);

                //2.获取用户名
                String username = map.get("attach");

                //3.更新订单状态
                seckillOrdersService.updatePayStatus(map.get("out_trade_no"),map.get("transaction_id"),username);


//            weixinPayService.notifyLogic(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
